import { useState, useEffect } from "react";
import {
  Status,
  useStatus,
  useCheckCollision,
  useLayout,
  useSpeed,
} from "./../../context";
import config from "../../config";
import "./index.css";
export default function Panel() {
  const speed = useSpeed();
  const status = useStatus();
  const { gridSize } = useLayout();
  const [score, setScore] = useState(0);
  const { isCollision } = useCheckCollision();

  // 关卡
  const level = Math.ceil(
    (score + config.scoreValue) / (config.foodSize * config.scoreValue)
  );

  // 速度
  const speedText = `${gridSize}px/${speed}ms`;

  // 更新分数
  useEffect(() => {
    if (status === Status.start && isCollision) {
      setScore(score + config.scoreValue);
    }
  }, [status, isCollision]);

  // 重置分数
  useEffect(() => {
    if (status === Status.reset) {
      setScore(0);
    }
  }, [status]);

  return (
    <div className="panel">
      <div className="score">分数：{score}</div>
      <div className="level">关卡：{level}</div>
      <div className="speed">速度：{speedText}</div>
    </div>
  );
}
